<?php

/**
 * ECSHOP 礼品详情
 *
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$smarty->assign('affiliate', $affiliate);

/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */
//参数处理
$goods_id = isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0; //商品ID


/*------------------------------------------------------ */
//-- 改变属性、数量时重新计算商品价格
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'price')
{
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '', 'qty' => 1);

	$type       = (isset($_REQUEST['type'])) ? intval($_REQUEST['type']) : 0;//是否烫金烫银 0否 1烫金，2烫银
	$number     = (intval($_REQUEST['number'])>0) ? intval($_REQUEST['number']) : 1;//购买数量

    if ($goods_id == 0)
    {
        $res['err_msg'] = $_LANG['err_change_attr'];
        $res['err_no']  = 1;
    }
    else
    {
        $res['qty'] = $number;
		$shop_price = get_shop_prices($goods_id);//商品价格
		if($type == 1 || $type == 2){
			$type_price	= get_type_prices($goods_id, $number);//烫金烫银总价格
		}else{
			$type_price = 0;
		}
		$total = ($shop_price*$number + $type_price);
		if($type == 1 || $type ==2){
			$type_name = ($type == 1)?'烫金总价':'烫银总价';
			$msg   = '&nbsp;&nbsp;<span style="color:#AAA;font-size:12px;">[(礼品总价'.price_format($shop_price*$number).'+'.$type_name.price_format($type_price).')]</span>';
		}
		$format_total = price_format($total).$msg;

        $res['result'] = $format_total;
    }

    die($json->encode($res));
}

/*------------------------------------------------------ */
//-- 改变套餐数量时，重新计算商品价格
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'taocan_price')
{

    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '', 'qty' => 1);

    $attr_id    = isset($_REQUEST['attr']) ? explode(',', $_REQUEST['attr']) : array();
	$gmid      = isset($_REQUEST['gmid']) ? explode('|', $_REQUEST['gmid']) : array();
	
    $number   = 1 ;
	
    if (count($gmid) <= 0)
    {
        $res['err_msg'] = $_LANG['err_change_attr'];
        $res['err_no']  = 1;
    }
    else
    {
		$rs = '您已选购产品：<br/>';
		$total = 0;
		foreach($gmid as $key=>$da){
			
			$gm = explode('#', $da);
			$goods_id = intval($gm[0]);
			if(count($gm)>2&&$gm[2]!=''){
				$attr_id = explode(',',$gm[2]);
			}
			if($goods_id >0){
				$shop_price  = get_final_price($goods_id, $number, true, $attr_id , $gm[1]);
				$total +=$shop_price;
				$rs .= '&nbsp;&nbsp;&nbsp;&nbsp;'.$_LANG['goods_sn'].get_goods_sn($goods_id).'&nbsp;&nbsp;&nbsp;&nbsp;价格：<font style="color:red;">'.price_format($shop_price * $number).'</font><br/>';
			}
		}
		$total = price_format($total);
		$rs .= '&nbsp;&nbsp;&nbsp;&nbsp;总计：<font style="color:red;">'.$total.'</font><br/>';
		$res['result'] = $rs;
    }

    die($json->encode($res));
}

/*------------------------------------------------------ */
//-- 商品购买记录ajax处理
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'gotopage')
{
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '');

    $goods_id   = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    $page    = (isset($_REQUEST['page'])) ? intval($_REQUEST['page']) : 1;

    if (!empty($goods_id))
    {
        $need_cache = $GLOBALS['smarty']->caching;
        $need_compile = $GLOBALS['smarty']->force_compile;

        $GLOBALS['smarty']->caching = false;
        $GLOBALS['smarty']->force_compile = true;

        /* 商品购买记录 */
        $sql = 'SELECT u.user_name, og.goods_count, og.goods_number, oi.add_time, IF(oi.order_status IN (2, 3, 4), 0, 1) AS order_status ' .
               'FROM ' . $ecs->table('order_info') . ' AS oi LEFT JOIN ' . $ecs->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $ecs->table('order_goods') . ' AS og ' .
               'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $goods_id . ' ORDER BY oi.add_time DESC LIMIT ' . (($page > 1) ? ($page-1) : 0) * 5 . ',5';
        $bought_notes = $db->getAll($sql);

        foreach ($bought_notes as $key => $val)
        {
            $bought_notes[$key]['add_time'] = local_date("Y-m-d G:i:s", $val['add_time']);
        }

        $sql = 'SELECT count(*) ' .
               'FROM ' . $ecs->table('order_info') . ' AS oi LEFT JOIN ' . $ecs->table('users') . ' AS u ON oi.user_id = u.user_id, ' . $ecs->table('order_goods') . ' AS og ' .
               'WHERE oi.order_id = og.order_id AND ' . time() . ' - oi.add_time < 2592000 AND og.goods_id = ' . $goods_id;
        $count = $db->getOne($sql);


        /* 商品购买记录分页样式 */
        $pager = array();
        $pager['page']         = $page;
        $pager['size']         = $size = 5;
        $pager['record_count'] = $count;
        $pager['page_count']   = $page_count = ($count > 0) ? intval(ceil($count / $size)) : 1;;
        $pager['page_first']   = "javascript:gotoBuyPage(1,$goods_id)";
        $pager['page_prev']    = $page > 1 ? "javascript:gotoBuyPage(" .($page-1). ",$goods_id)" : 'javascript:;';
        $pager['page_next']    = $page < $page_count ? 'javascript:gotoBuyPage(' .($page + 1) . ",$goods_id)" : 'javascript:;';
        $pager['page_last']    = $page < $page_count ? 'javascript:gotoBuyPage(' .$page_count. ",$goods_id)"  : 'javascript:;';

        $smarty->assign('notes', $bought_notes);
        $smarty->assign('pager', $pager);


        $res['result'] = $GLOBALS['smarty']->fetch('library/bought_notes.lbi');

        $GLOBALS['smarty']->caching = $need_cache;
        $GLOBALS['smarty']->force_compile = $need_compile;
    }

    die($json->encode($res));
}

/*------------------------------------------------------ */
//-- 添加礼品到购物车
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'add_gfit_to_cart')
{
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('error' => '', 'message' => '失败');

    $goods_id   = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
	$type       = (isset($_REQUEST['type'])) ? intval($_REQUEST['type']) : 0;//是否烫金烫银 0否 1烫金，2烫银
	$number     = (intval($_REQUEST['number'])>0) ? intval($_REQUEST['number']) : 1;//购买数量
	
	if(add_gift_goods_to_cart($goods_id, $number , $type )){
		$res['message']    = '添加成功';
		$res['error']      = 0;
		//$_SESSION['flow_type'] = CART_GENERAL_GOODS;
	}else{
		$res['message']    = $GLOBALS['err']->last_message();
		$res['error']      = $GLOBALS['err']->error_no;
	}
	die($json->encode($res));

}
/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */

$cache_id = $goods_id .'-gift_goods-' . $_SESSION['user_rank'].'-'.$_CFG['lang'];
$cache_id = sprintf('%X', crc32($cache_id));
if (!$smarty->is_cached('gift_goods.dwt', $cache_id))
{
    $smarty->assign('image_width',  $_CFG['image_width']);
    $smarty->assign('image_height', $_CFG['image_height']);
    $smarty->assign('helps',        get_shop_help()); // 网店帮助
    $smarty->assign('cfg',          $_CFG);
	$smarty->assign('top_goods',        get_gift_top10());             // 销售排行

	$goodslist = false;
	$goods     = false;

	if( $goods_id > 0 ){
		$goods = get_gift_goods_info($goods_id);
	}

    if ($goods === false)
    {
        /* 如果没有找到任何记录则跳回到首页 */
        ecs_header("Location: ./\n");
        exit;
    }
    else
    {

        $shop_price   = $goods['shop_price'];
        /* 购买该商品可以得到多少钱的红包 */
        if ($goods['bonus_type_id'] > 0)
        {
            $time = gmtime();
            $sql = "SELECT type_money FROM " . $ecs->table('bonus_type') .
                    " WHERE type_id = '$goods[bonus_type_id]' " .
                    " AND send_type = '" . SEND_BY_GOODS . "' " .
                    " AND send_start_date <= '$time'" .
                    " AND send_end_date >= '$time'";
            $goods['bonus_money'] = floatval($db->getOne($sql));
            if ($goods['bonus_money'] > 0)
            {
                $goods['bonus_money'] = price_format($goods['bonus_money']);
            }
        }

        $smarty->assign('goods',              $goods);
        $smarty->assign('goods_id',           $goods['goods_id']);
//print_r($goods);exit;
        /* meta */
        $smarty->assign('keywords',           htmlspecialchars($goods['goods_name']));
        $smarty->assign('description',        htmlspecialchars($goods['goods_name']));

        /* current position */
        $smarty->assign('page_title',		'');  // 页面标题
		$smarty->assign('ur_here',			'<a href=".">首页</a> > <a href="exchange.php">礼品商城</a> > <span>'.$goods['goods_name'].'</span>');//面包屑

        //$smarty->assign('pictures',            get_goods_gallery($goods_id));                    // 商品相册
        //$smarty->assign('bought_goods',        get_also_bought($goods_id));                      // 购买了该商品的用户还购买了哪些商品
        //$smarty->assign('goods_rank',          get_goods_rank($goods_id));                       // 商品的销售排名
		$smarty->assign('id',				   $goods_id);  //商品ID

        //获取tag
        $smarty->assign('tags',                array()); // 商品的标记

        assign_dynamic('gift_goods');
		// 商品烫金烫银优惠价格区间
		
		$smarty->assign('volume_price_list',	get_number_price_list($goods_id));
		
		//同分类下的商品列表
		$smarty->assign('goodslist',		$goodslist);
		
    }
}

/* 记录浏览历史 */
if (!empty($_COOKIE['ECS']['history']))
{
    $history = explode(',', $_COOKIE['ECS']['history']);

    array_unshift($history, $goods_id);
    $history = array_unique($history);

    while (count($history) > $_CFG['history_number'])
    {
        array_pop($history);
    }

    setcookie('ECS[history]', implode(',', $history), gmtime() + 3600 * 24 * 30);
}
else
{
    setcookie('ECS[history]', $goods_id, gmtime() + 3600 * 24 * 30);
}

$smarty->assign('click_count',  get_click_count($goods_id));// 点击数

/* 更新点击次数 */
$db->query('UPDATE ' . $ecs->table('gift_goods') . " SET click_count = click_count + 1 WHERE goods_id = '$goods_id'");

$smarty->assign('now_time',  gmtime());           // 当前系统时间
$smarty->display('gift_goods.dwt',      $cache_id);

/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */


/**
 * 获得商品选定的属性的附加总价格
 *
 * @param   integer     $goods_id
 * @param   array       $attr
 *
 * @return  void
 */
function get_attr_amount($goods_id, $attr)
{
    $sql = "SELECT SUM(attr_price) FROM " . $GLOBALS['ecs']->table('goods_attr') .
        " WHERE goods_id='$goods_id' AND " . db_create_in($attr, 'goods_attr_id');

    return $GLOBALS['db']->getOne($sql);
}

function get_click_count($goods_id = 0){
	    $sql = "SELECT click_count FROM " . $GLOBALS['ecs']->table('gift_goods') .
        " WHERE goods_id='$goods_id' ";
    return $GLOBALS['db']->getOne($sql);
}


/**
 * 获得分类的信息
 *
 * @param   integer $cat_id
 *
 * @return  void
 */
function get_cat_info($cat_id)
{
    return $GLOBALS['db']->getRow('SELECT * FROM ' . $GLOBALS['ecs']->table('gift_cat') .
        " WHERE cat_id = '$cat_id'");
}

/**
 * 获得分类下的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function category_get_goods($cat_id = '', $size = 10 , $page = 1)
{
    return false;
}

function get_gift_goods_info($goods_id = 0){
	
	$sql = 'SELECT g.* FROM ' . $GLOBALS['ecs']->table('gift_goods') . ' AS g ' .
            "WHERE g.goods_id = '$goods_id' AND g.is_on_sale = 1 " ;
	$row = $GLOBALS['db']->getRow($sql);

	if ($row !== false)
    {

		/* 修正上架时间显示 */
        $row['add_time']      = local_date($GLOBALS['_CFG']['date_format'], $row['ctime']);

		/* 修正积分：转换为可使用多少积分（原来是可以使用多少钱的积分） */
        $row['integral']      = $GLOBALS['_CFG']['integral_scale'] ? round($row['integral'] * 100 / $GLOBALS['_CFG']['integral_scale']) : 0;

		 /* 修正商品图片 */
        $row['goods_img']   = get_image_path($goods_id, $row['goods_img']);
        $row['goods_thumb'] = get_image_path($goods_id, $row['goods_thumb'], true);

		/* 获得商品的销售价格 */
        $row['format_market_price']     = price_format($row['market_price']);
        $row['format_shop_price']		= price_format($row['shop_price']);

		$row['goods_cat_name'] = '';//get_bb_name($row['bb_id']);//礼品分类名称

		return $row;
	}else{
		return false;
	}

}

/**
 * 添加礼品到购物车
 *
 * @access  public
 * @param   integer $goods_id   礼品编号
 * @param   integer $number     礼品数量
 * @return  boolean
 */
function add_gift_goods_to_cart($goods_id , $number = 1,$type = 0)
{
    $GLOBALS['err']->clean();

    /* 取得商品信息 */
    $sql = "SELECT g.* ".
            " FROM " .$GLOBALS['ecs']->table('gift_goods'). " AS g ".
            " WHERE g.goods_id = '$goods_id'";
	$goods = $GLOBALS['db']->getRow($sql);

    if (empty($goods))
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS);

        return false;
    }

	    /* 是否正在销售 */
    if ($goods['is_on_sale'] == 0)
    {
        $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE);

        return false;
    }

	if($goods){
		/* 初始化要插入购物车的基本件数据 */
		$parent = array(
			'user_id'       => $_SESSION['user_id'],
			'session_id'    => SESS_ID,
			'parent_id'     => 0,
			'goods_id'      => $goods_id,
			'goods_sn'      => $goods['goods_sn'],
			'goods_name'    => addslashes($goods['goods_name']),
			'market_price'  => $goods['market_price']*$number,
			'goods_price'   => $goods['shop_price']*$number,
			'goods_count'   => $number,
			'goods_number'  => 1,
			'goods_attr'    => '',
			'goods_attr_id' => $type,
			'is_real'       => 1,
			'extension_code'=> 'gift_goods_buy',
			'is_gift'       => 0,
			'rec_type'      => CART_GENERAL_GOODS,
			'goods_img'		=> 0, //产品稿件图片ID
			'act_id'		=> 0 //稿件套装ID
		);
		
		if($type == 1){
			$parent['goods_model']  = '烫金';
		}else if($type == 2){
			$parent['goods_model']  = '烫银';
		}
		$parent['goods_attr'] = '包装方式：'.$goods['goods_pack'];

		if($type == 1 || $type == 2){
			$parent['img_price2'] = get_type_prices($goods_id, $number);//烫金烫银总计价
		}else{
			$parent['img_price2'] = 0;
		}
		$parent['img_price'] = $parent['img_price2'];

		 $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('cart'), $parent, 'INSERT');
	}

    return true;
}


/*获取礼品烫金烫银总价格 */
function get_type_prices( $goods_id , $number){
	$sql = 'select volume_price,type FROM ' . $GLOBALS['ecs']->table('gift_goods_price') .
		" WHERE goods_id ='$goods_id' AND (number_min <= $number && number_max >= $number )";
	$data = $GLOBALS['db']->getRow($sql);
	if($data){
		if($data['type'] == 1){
			return $data['volume_price'];
		}else{
			return $data['volume_price']*$number;
		}
	}else{
		return 0;
	}
}

/*获取礼品价格*/
function get_shop_prices($goods_id = 0){
	$sql = 'select shop_price FROM ' . $GLOBALS['ecs']->table('gift_goods') .
		" WHERE goods_id ='$goods_id'";
	$shop_price = $GLOBALS['db']->getOne($sql);//帮我设计稿件价格。		
	return $shop_price;
}

/**
 * 调用当前分类的销售排行榜
 *
 * @access  public
 * @param   string  $cats   查询的分类
 * @return  array
 */
function get_gift_top10($cats = '')
{

    $where = !empty($cats) ? "AND g.cat_id = '$cats' " : '';

    /* 排行统计的时间 */
    switch ($GLOBALS['_CFG']['top10_time'])
    {
        case 1: // 一年
            $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 365 * 86400) . "'";
        break;
        case 2: // 半年
            $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 180 * 86400) . "'";
        break;
        case 3: // 三个月
            $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 90 * 86400) . "'";
        break;
        case 4: // 一个月
            $top10_time = "AND o.order_sn >= '" . date('Ymd', gmtime() - 30 * 86400) . "'";
        break;
        default:
            $top10_time = '';
    }

    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.goods_thumb, SUM(og.goods_number) as goods_number ' .
           'FROM ' . $GLOBALS['ecs']->table('gift_goods') . ' AS g, ' .
                $GLOBALS['ecs']->table('order_info') . ' AS o, ' .
                $GLOBALS['ecs']->table('order_goods') . ' AS og ' .
           "WHERE g.is_on_sale = 1 $where $top10_time " ;

    $sql .= ' AND og.order_id = o.order_id AND og.goods_id = g.goods_id AND og.extension_code = "gift_goods_buy"' .
           "AND (o.order_status = '" . OS_CONFIRMED .  "' OR o.order_status = '" . OS_SPLITED . "') " .
           "AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') " .
           "AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') " .
           'GROUP BY g.goods_id ORDER BY goods_number DESC, g.goods_id DESC LIMIT ' . $GLOBALS['_CFG']['top_number'];
           
    $arr = $GLOBALS['db']->getAll($sql);

    for ($i = 0, $count = count($arr); $i < $count; $i++)
    {
        $arr[$i]['short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
                                    sub_str($arr[$i]['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $arr[$i]['goods_name'];
        $arr[$i]['url']     = 'gift_goods.php?id='.$arr[$i]['goods_id'];
        $arr[$i]['thumb']	= get_image_path($arr[$i]['goods_id'], $arr[$i]['goods_thumb'],true);
		$arr[$i]['market_price'] = price_format($arr[$i]['market_price']);
		$arr[$i]['shop_price']   = price_format($arr[$i]['shop_price']);
    }

    return $arr;
}

function get_number_price_list($goods_id){
	
	$sql = "SELECT * FROM " . $GLOBALS['ecs']->table('gift_goods_price') .
		" WHERE goods_id = '$goods_id' ORDER BY number_min ASC";
	
	return $GLOBALS['db']->getAll($sql);
}

?>